import { ProCard, ProLayout } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Outlet, useNavigate, Link, useLocation } from 'react-router-dom-v5-compat';
import { LogoutOutlined, MenuFoldOutlined, MenuUnfoldOutlined, SettingFilled } from '@ant-design/icons';
import useUserStore, { useTokenStore } from 'store/user';
import useLogin from 'hooks/useLogin';
import { getLoginUserInfo } from 'apis/common';
import Password from 'pages/home/userCenter/Password';
import { OnlyLogo, TitleLogo } from 'icons';
import { Avatar, Dropdown, Menu, MenuProps, Modal, Popconfirm, Tooltip } from 'antd';
import { divide } from 'lodash';
import defaultProps from './_defaultProps';

// export default
function PageLayout(): JSX.Element {
    const navigate = useNavigate();
    const location = useLocation();
    const [collapsed, setCollapsed] = useState(false);
    const [pageTitle, setPageTitle] = useState('');
    const { updateUserInfo, updateMenu, userInfo, menuMap, menus } = useUserStore();
    const { currentTenant, setCurrentTenant } = useTokenStore();
    const { token, handleLogin, claerToken } = useLogin();

    function isMatchAnnotation(url) {
        // 修正后的正则表达式
        const pattern = /^\/tasks\/(\d+)\/jobs\/(\d+)\/subtask\/(\d+)\/action\/(\w+)$/;
        return pattern.test(url);
    }

    function matchRouter(path: string): void {
        const item = Object.keys(menuMap).find((v) => v === path);
        if (item) {
            setPageTitle(menuMap[item].label);
        } else if (path === '/') {
            matchRouter('/tasks');
        }
    }
    const beforeIntoApp = (res: API.LoginUserInfoResponseType) => {
        updateUserInfo(res);
        if (res?.tenants?.length === 1) {
            setCurrentTenant(res?.tenants?.[0]?.tenantId || '');
        } else if (res?.tenants?.length) {
            // 需要选择
        }
        initMenu();
    };

    const initMenu = () => {
        defaultProps.route.routes = menus.map((v) => {
            if (v.children && v.children.length) {
                return {
                    name: v.label,
                    path: v.path,
                    key: v.key,
                    children: v.children.map((item) => ({
                        name: item.label,
                        path: item.path,
                        key: item.key,
                    })),
                };
            }
            return {
                name: v.label,
                path: v.path,
                key: v.key,
            };
        });
    };
    const getUserInfo = async () => {
        const res = await getLoginUserInfo();
        beforeIntoApp(res);
    };
    useEffect(() => {
        matchRouter(location.pathname);
    }, [location]);
    useEffect(() => {
        // 是否登录
        if (!token) {
            handleLogin();
        } else {
            getUserInfo();
        }
    }, [token]);
    return (
        <div className='h-100vh w-100vw'>
            <ProLayout
                title=''
                logo={collapsed ? <OnlyLogo /> : <TitleLogo />}
                siderWidth={246}
                onMenuHeaderClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    navigate('/');
                }}
                token={{
                    pageContainer: {
                        paddingBlockPageContainerContent: 0,
                        paddingInlinePageContainerContent: 0,
                    },
                }}
                collapsed={collapsed}
                collapsedButtonRender={() =>
                    collapsed ? (
                        <MenuUnfoldOutlined
                            style={{ position: 'absolute', right: '-25px', top: '25px' }}
                            onClick={() => {
                                setCollapsed(false);
                            }}
                        />
                    ) : (
                        <MenuFoldOutlined
                            style={{ position: 'absolute', right: '-25px', top: '25px' }}
                            onClick={() => {
                                setCollapsed(true);
                            }}
                        />
                    )
                }
                {...defaultProps}
                location={location}
                avatarProps={{
                    src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                    title: (
                        <div
                            className='flex flex-col text-left cursor-pointer'
                            onClick={() => {
                                navigate('/userCenter');
                            }}
                        >
                            <span className='font-500 color-#000000'>{userInfo?.name}</span>
                            <span className='color-#666'>{userInfo?.roles[0]?.roleName}</span>
                        </div>
                    ),
                    size: 'large',
                }}
                actionsRender={() => (
                    <Tooltip title='退出登录'>
                        <LogoutOutlined
                            onClick={() => {
                                claerToken();
                                handleLogin();
                            }}
                        />
                    </Tooltip>
                )}
                menuItemRender={(menuItemProps, defaultDom) => {
                    if (menuItemProps.isUrl) {
                        return defaultDom;
                    }
                    if (menuItemProps.path && location.pathname !== menuItemProps.path) {
                        return (
                            <Link to={menuItemProps.path} target={menuItemProps.target}>
                                {defaultDom}
                            </Link>
                        );
                    }
                    return defaultDom;
                }}
            >
                <ProCard
                    title={isMatchAnnotation(location.pathname) ? null : pageTitle}
                    headerBordered
                    headStyle={{
                        height: '68px',
                        paddingLeft: '45px',
                    }}
                    bodyStyle={{
                        padding: 0,
                        // height: 'calc(100vh - 68px)',
                    }}
                >
                    {/* <Outlet /> */}
                    {/* <ProCard
                        style={{
                            height: '100%',
                            // minHeight: 800,
                        }}
                        bodyStyle={{
                            padding: 0,
                        }}
                    > */}
                    <Outlet />
                    {!!token && Number(userInfo?.restPasswdTag) === 1 ? (
                        <Password
                            visible
                            title='设置密码'
                            modalProps={{
                                closeIcon: null,
                            }}
                            successCallback={getUserInfo}
                            hideOldPassword
                        />
                    ) : null}
                    {/* </ProCard> */}
                </ProCard>
                {/* </PageContainer> */}
            </ProLayout>
        </div>
    );
}

export default React.memo(PageLayout);
